package com.ekuaitu.kuaitu.fragment;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.model.LatLng;
import com.ekuaitu.kuaitu.R;
import com.ekuaitu.kuaitu.activity.CarCertificateActivity;
import com.ekuaitu.kuaitu.activity.MainActivity;
import com.ekuaitu.kuaitu.api.ApiStore;
import com.ekuaitu.kuaitu.api.UrlConstant;
import com.ekuaitu.kuaitu.bean.AlipayPreBean;
import com.ekuaitu.kuaitu.bean.DepositCarResultEvent;
import com.ekuaitu.kuaitu.bean.WXPreBean;
import com.ekuaitu.kuaitu.payment.AlipayUtils;
import com.ekuaitu.kuaitu.payment.WXPayUtils;
import com.ekuaitu.kuaitu.utils.Constants;
import com.ekuaitu.kuaitu.utils.MyApplication;
import com.ekuaitu.kuaitu.utils.SharedPreferencesKey;
import com.ekuaitu.kuaitu.utils.SharedPreferencesUtils;
import com.ekuaitu.kuaitu.utils.Toast.ToastCompat;
import com.umeng.analytics.MobclickAgent;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.autolayout.AutoRelativeLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * A simple {@link Fragment} subclass.
 */
public class DepositCarFragment extends Fragment implements AMapLocationListener {


    @BindView(R.id.carDeposit_ll)
    AutoLinearLayout carDepositLl;
    @BindView(R.id.carDeposit_weiXin)
    ImageView carDepositWeiXin;
    @BindView(R.id.car_deposit_wx)
    AutoRelativeLayout carDepositWx;
    @BindView(R.id.car_deposit_zfb)
    AutoRelativeLayout carDepositZfb;
    @BindView(R.id.car_deposit_line)
    View carDepositLine;
    @BindView(R.id.carDeposit_button_weiXin)
    RadioButton carDepositButtonWeiXin;
    @BindView(R.id.carDeposit_button_zfb)
    RadioButton carDepositButtonZfb;
    @BindView(R.id.pay_Cardeposit)
    TextView payCardeposit;
    @BindView(R.id.carDeposit_money)
    TextView carDepositMoney;
    @BindView(R.id.progress_bar)
    RelativeLayout progressBar;
    private Context mContext;
    private int payMethod = 0;
    private String identityStatus;
    private String licenseStatus;
    private String depositStatus;
    private LatLng curPosition;
    private AMapLocationClient mLocationClient;
    private AMapLocationClientOption mLocationOption;

    public DepositCarFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        mContext = getContext();
        mLocationClient = new AMapLocationClient(getContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(this);
        mLocationOption = new AMapLocationClientOption();
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationOption.setOnceLocation(true);
        mLocationClient.setLocationOption(mLocationOption);
        mLocationClient.startLocation();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_certify_deposit, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //显示可用的支付方式
        if (SharedPreferencesUtils.getInstance(mContext).getIntValue(SharedPreferencesKey.IS_WXPAY_OPEN) == 1 && SharedPreferencesUtils.getInstance(mContext).getIntValue(SharedPreferencesKey.IS_ALIPAY_OPEN) == 1) {
            carDepositWx.setVisibility(View.VISIBLE);
            carDepositZfb.setVisibility(View.VISIBLE);
            carDepositLine.setVisibility(View.VISIBLE);
            carDepositButtonWeiXin.setChecked(true);
            carDepositButtonZfb.setChecked(false);
            payMethod = 1;
        } else if (SharedPreferencesUtils.getInstance(mContext).getIntValue(SharedPreferencesKey.IS_WXPAY_OPEN) == 1 && SharedPreferencesUtils.getInstance(mContext).getIntValue(SharedPreferencesKey.IS_ALIPAY_OPEN) == 0) {
            carDepositWx.setVisibility(View.VISIBLE);
            carDepositZfb.setVisibility(View.GONE);
            carDepositLine.setVisibility(View.GONE);
            carDepositButtonWeiXin.setChecked(true);
            carDepositButtonZfb.setChecked(false);
            payMethod = 1;
        } else if (SharedPreferencesUtils.getInstance(mContext).getIntValue(SharedPreferencesKey.IS_WXPAY_OPEN) == 0 && SharedPreferencesUtils.getInstance(mContext).getIntValue(SharedPreferencesKey.IS_ALIPAY_OPEN) == 1) {
            carDepositWx.setVisibility(View.GONE);
            carDepositZfb.setVisibility(View.VISIBLE);
            carDepositLine.setVisibility(View.GONE);
            carDepositButtonWeiXin.setChecked(false);
            carDepositButtonZfb.setChecked(true);
            payMethod = 2;
        } else if (SharedPreferencesUtils.getInstance(mContext).getIntValue(SharedPreferencesKey.IS_WXPAY_OPEN) == 0 && SharedPreferencesUtils.getInstance(mContext).getIntValue(SharedPreferencesKey.IS_ALIPAY_OPEN) == 0) {
            carDepositWx.setVisibility(View.GONE);
            carDepositZfb.setVisibility(View.GONE);
            carDepositLine.setVisibility(View.GONE);
            payMethod = 0;
        }


        carDepositButtonWeiXin.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    payMethod = 1;
                    carDepositButtonZfb.setChecked(false);
                }
            }
        });

        carDepositButtonZfb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    payMethod = 2;
                    carDepositButtonWeiXin.setChecked(false);
                }
            }
        });

        carDepositMoney.setText(SharedPreferencesUtils.getInstance(mContext).getIntValue(SharedPreferencesKey.DEPOSIT_CAR) / 100 + "");
    }

    @Subscribe
    public void onPayResult(DepositCarResultEvent event) {
        progressBar.setVisibility(View.GONE);
        identityStatus = SharedPreferencesUtils.getInstance(mContext).getStringValue(SharedPreferencesKey.IDENTITY_STATUS);
        licenseStatus = SharedPreferencesUtils.getInstance(mContext).getStringValue(SharedPreferencesKey.LICENSE_STATUS);

        if (event.payResult == 0) {
            CarCertificateActivity activity = (CarCertificateActivity) getActivity();
            switch (identityStatus) {
                //身份证审核中
                //身份证审核成功
                case "11":
                case "13":
                    switch (licenseStatus) {
                        //驾驶证未审核
                        //驾驶证失败
                        case "10":
                        case "12":
                            activity.mVp.setCurrentItem(2);
                            break;
                        //驾驶证审核中
                        //驾驶证审核成功
                        case "11":
                        case "13":
                            SharedPreferencesUtils.getInstance(mContext).putIntValue(SharedPreferencesKey.USER_TRIP_METHOD, 1);
                            startActivity(new Intent(mContext, MainActivity.class));
                            activity.finish();
                            break;
                    }
                    break;
                //身份证未审核
                //身份证失败
                case "10":
                case "12":
                    activity.mVp.setCurrentItem(1);
                    break;
            }
        } else {
            CarCertificateActivity activity = (CarCertificateActivity) getActivity();
            activity.mVp.setCurrentItem(0);
            activity.tvTitle.setText("缴保证金");
            //支付失败，还在当前交保证金界面，判断身份和驾照状态显示头图片
            switch (identityStatus) {
                //身份证审核中
                //身份证审核成功
                case "11":
                case "13":
                    switch (licenseStatus) {
                        //驾驶证未审核
                        //驾驶证失败
                        case "10":
                        case "12":
                            activity.certificateLlJbzj.setVisibility(View.GONE);
                            activity.certificateLlSmrz.setVisibility(View.GONE);
                            activity.certificateLlZzhy.setVisibility(View.GONE);
                            activity.certificateLlJbzj10.setVisibility(View.VISIBLE);
                            activity.certificateLlJbzj11.setVisibility(View.GONE);
                            break;
                        //驾驶证审核中
                        //驾驶证审核成功
                        case "11":
                        case "13":
                            activity.certificateLlJbzj.setVisibility(View.GONE);
                            activity.certificateLlSmrz.setVisibility(View.GONE);
                            activity.certificateLlZzhy.setVisibility(View.GONE);
                            activity.certificateLlJbzj10.setVisibility(View.GONE);
                            activity.certificateLlJbzj11.setVisibility(View.VISIBLE);
                            break;
                    }
                    break;
                //身份证未审核
                //身份证失败
                case "10":
                case "12":
                    switch (licenseStatus) {
                        //驾驶证未审核
                        //驾驶证失败
                        //驾驶证审核中
                        //驾驶证审核成功
                        case "11":
                        case "13":
                        case "10":
                        case "12":
                            activity.certificateLlJbzj.setVisibility(View.VISIBLE);
                            activity.certificateLlSmrz.setVisibility(View.GONE);
                            activity.certificateLlZzhy.setVisibility(View.GONE);
                            activity.certificateLlJbzj10.setVisibility(View.GONE);
                            activity.certificateLlJbzj11.setVisibility(View.GONE);
                            break;
                    }
                    break;
            }

        }
    }

    @OnClick({R.id.pay_Cardeposit})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.pay_Cardeposit:
                MobclickAgent.onEvent(this.getActivity(), Constants.PAY_DEPOSIT);
                //缴纳保证金
                switch (payMethod) {
                    case 1:
                        getWXpayParams(SharedPreferencesUtils.getInstance(mContext).getIntValue(SharedPreferencesKey.DEPOSIT_CAR) + "");
                        break;
                    case 2:
                        getAlipayParams(SharedPreferencesUtils.getInstance(mContext).getIntValue(SharedPreferencesKey.DEPOSIT_CAR) + "");
                        break;
                }
                break;
        }
    }

    private void getWXpayParams(String chargeValue) {
        String longitude;
        String latitude;
        if (curPosition == null) {
            if (MainActivity.curPosition != null) {
                longitude = MainActivity.curPosition.longitude + "";
                latitude = MainActivity.curPosition.latitude + "";
            } else {
                longitude = "";
                latitude = "";
            }
        } else {
            longitude = curPosition.longitude + "";
            latitude = curPosition.latitude + "";
        }
        progressBar.setVisibility(View.VISIBLE);
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).weChatDeposit(MyApplication.getInstance().getRequestFieldMap(), chargeValue, "2", longitude, latitude, "1").enqueue(new Callback<WXPreBean>() {
            @Override
            public void onResponse(Call<WXPreBean> call, Response<WXPreBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        SharedPreferencesUtils.getInstance(mContext).putIntValue(SharedPreferencesKey.USER_PAY_TYPE, 0);
                        WXPreBean.AttachmentBean.BeanBean orderInfo = response.body().getAttachment().getBean();
                        WXPayUtils wxPayUtils = new WXPayUtils(mContext);
                        wxPayUtils.wxPay(orderInfo);
                    } else {
                        progressBar.setVisibility(View.GONE);
                        ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_LONG).show();
                    }
                } else {
                    progressBar.setVisibility(View.GONE);
                    ToastCompat.makeText(mContext, getResources().getString(R.string.serverError), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<WXPreBean> call, Throwable t) {
                progressBar.setVisibility(View.GONE);
                ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void getAlipayParams(String chargeValue) {
        String longitude;
        String latitude;
        if (curPosition == null) {
            longitude = "";
            latitude = "";
        } else {
            longitude = curPosition.longitude + "";
            latitude = curPosition.latitude + "";
        }
        progressBar.setVisibility(View.VISIBLE);
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).aliPayDeposit(MyApplication.getInstance().getRequestFieldMap(), chargeValue, "1", longitude, latitude, "1").enqueue(new Callback<AlipayPreBean>() {
            @Override
            public void onResponse(Call<AlipayPreBean> call, Response<AlipayPreBean> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().getStatus() == 200) {
                        SharedPreferencesUtils.getInstance(mContext).putIntValue(SharedPreferencesKey.USER_PAY_TYPE, 0);
                        String orderInfo = response.body().getAttachment().getStr();
                        AlipayUtils alipayUtils = new AlipayUtils(getActivity());
                        alipayUtils.aliPay(orderInfo);
                    } else {
                        progressBar.setVisibility(View.GONE);
                        ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_LONG).show();
                    }
                } else {
                    progressBar.setVisibility(View.GONE);
                    ToastCompat.makeText(mContext, getResources().getString(R.string.serverError), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<AlipayPreBean> call, Throwable t) {
                progressBar.setVisibility(View.GONE);
                ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_SHORT).show();
            }
        });
    }

    //viewpager的监听器打开位置为0的 mVp.setCurrentItem(0)不会触发监听器。
    private void deposit() {

    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null && aMapLocation.getErrorCode() == 0) {
            curPosition = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());
        } else {
            mLocationClient.startLocation();
        }
    }
}
